package io.renren.modules.doc.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.postgresql.util.PGobject;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Base64;

/**
 * PostgreSQL vecf16类型处理器
 * 用于处理Java的byte[]类型和PostgreSQL的vecf16类型之间的转换
 */
@MappedTypes(byte[].class)
public class VecF16TypeHandler extends BaseTypeHandler<byte[]> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, byte[] parameter, JdbcType jdbcType) throws SQLException {
        PGobject pgObject = new PGobject();
        pgObject.setType("vecf16");
        
        // 将byte[]转换为vecf16格式的字符串
        StringBuilder sb = new StringBuilder("[");
        for (int j = 0; j < parameter.length && j < 384; j++) {
            if (j > 0) {
                sb.append(",");
            }
            // 将byte值转换为浮点数 (-1.0 到 1.0 范围)
            float value = parameter[j] / 127.0f;
            sb.append(String.format("%.6f", value));
        }
        sb.append("]");
        
        pgObject.setValue(sb.toString());
        ps.setObject(i, pgObject);
    }

    @Override
    public byte[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return parseVectorString(value);
    }

    @Override
    public byte[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return parseVectorString(value);
    }

    @Override
    public byte[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return parseVectorString(value);
    }
    
    /**
     * 解析向量格式的字符串为byte[]
     */
    private byte[] parseVectorString(String vectorStr) {
        if (vectorStr == null || vectorStr.isEmpty()) {
            return new byte[384]; // 返回空向量
        }
        
        try {
            // 去除开头的'['和结尾的']'
            String content = vectorStr.trim();
            if (content.startsWith("[")) {
                content = content.substring(1);
            }
            if (content.endsWith("]")) {
                content = content.substring(0, content.length() - 1);
            }
            
            // 按逗号分割并转换为byte数组
            String[] values = content.split(",");
            byte[] result = new byte[values.length];
            
            for (int i = 0; i < values.length; i++) {
                // 将浮点数转换回byte值 (-1.0 到 1.0 范围)
                float value = Float.parseFloat(values[i].trim());
                result[i] = (byte)(value * 127.0f);
            }
            
            return result;
        } catch (Exception e) {
            // 解析失败时返回空向量
            return new byte[384];
        }
    }
}
